package com.ruoyi.common.utils;

import javax.mail.*;
import javax.mail.internet.*;
import java.io.IOException;
import java.util.Properties;

public class EmailUtils {

    private static final String SMTP_HOST = "smtp.qq.com";
    private static final int SMTP_PORT = 465;
    private static final String username = "879829564@qq.com";
    private static final String authCode = "krjercjfaldpbbjc";

    public static void send(String toEmail, String subject, String content) throws MessagingException, IOException {
        send(toEmail,subject,content,false,null);
    }

    public static void send(
                            String toEmail, String subject,
                            String content, boolean isHtml,
                            String[] attachments) throws MessagingException, IOException {

        Properties props = new Properties();
        props.put("mail.smtp.host", SMTP_HOST);
        props.put("mail.smtp.port", SMTP_PORT);
        props.put("mail.smtp.ssl.enable", "true");
        props.put("mail.smtp.auth", "true");

        Session session = Session.getInstance(props, new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, authCode);
            }
        });

        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(username));
        message.setRecipient(Message.RecipientType.TO, new InternetAddress(toEmail));
        message.setSubject(subject, "UTF-8");

        Multipart multipart = new MimeMultipart();

        // 添加正文
        MimeBodyPart textPart = new MimeBodyPart();
        textPart.setContent(content, isHtml ? "text/html;charset=UTF-8" : "text/plain;charset=UTF-8");
        multipart.addBodyPart(textPart);

        // 添加附件
        if (attachments != null) {
            for (String filePath : attachments) {
                MimeBodyPart attachmentPart = new MimeBodyPart();
                attachmentPart.attachFile(filePath);
                multipart.addBodyPart(attachmentPart);
            }
        }

        message.setContent(multipart);
        Transport.send(message);
    }

    public static void main(String[] args) {
        try {
            send(
                    "18130348118@163.com",
                    "测试主题",
                    "<h1>验证码：965236</h1>",
                    true,
                    new String[]{"D:/test.txt"}); // 附件路径
            System.out.println("发送成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
